<?php
/**
 * Created by PhpStorm.
 * User: caviar
 * Date: 2019/9/18
 * Time: 16:31
 */

namespace app\admin\service;

/**
 * Class Auth
 * @package app\admin\service
 * 权限控制
 */
class Auth
{
    /**
     * @param userID 获取rule表ID
     * @return rules
     */
    private function _auth_sel()
    {
        $group = db('auth_group_access')
            ->alias('access')
            ->where('uid',$this->user_id)
            ->join('auth_group group','access.group_id=group.id')
            ->field('rules')
            ->find();
        $rules = $group['rules'];
        return $rules;
    }

    /**
     * 输出menu数据
     */
    protected function _auth_menu()
    {
        $rules = $this->_auth_sel();
        if ($rules == 'all')
        {
            $auth_rule = db('auth_rule')
                ->where('status',1)
                ->order('collation','asc')
                ->select();
            $recursion_rules = recursion($auth_rule,0);
        }else{
            $auth_rule = db('auth_rule')
                ->where('id','in',$rules)
                ->where('grade','<>',0)
                ->where('status',1)
                ->order('collation','asc')
                ->select();
            $recursion_rules = recursion($auth_rule,0);
        }
        return $recursion_rules;
    }

    /**
     * @
     * 判断是否有访问方法的权限
     */
    protected function _authCheckMethod()
    {
        $rules = $this->_auth_sel();
        if ($rules == 'all'){return true;}
        $rulesArr = explode(",",$rules);
        $url = explode('.',$this->request->url());
        $rule = db('auth_rule')->where('name',$url[0])->field('id')->find();
        $rule_id = $rule['id'];
        foreach ($rulesArr as $value)
        {
            if ($value  == $rule_id)
            {
                return true;
            }
        }
        return $this->error('您还没有权限访问该方法!',url('index/index'));
    }

    /**
     * @ return true
     * 判断是否有访问该控制器的权限 --- all除外
     */
    protected function _authCheckController()
    {
        $rules = $this->_auth_sel();
        if ($rules == 'all'){return true;}
        $rule = db('auth_rule')->where([['id','in',$rules],['grade','in','0,1']])->field('name')->select();
        $controller = $this->request->controller();
        $lcfirst = lcfirst($controller);
        foreach ($rule as $key => $value)
        {
            if ($value['name'] == $lcfirst)
            {
                return true;
            }
        }
        return $this->error('您还没有权限访问该控制器!',url('index/index'));
    }



}